
from urllib.parse import urlencode, parse_qs
from urllib.request import urlopen
import logging
import json
from .exceptions import QQAPIError
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings
from . import constants
logger = logging.getLogger('django')
class OAuthQQ(object):
    '''QQ认证辅助工据类
    Step1：获取Authorization Code
    请求地址：
    PC网站：https://graph.qq.com/oauth2.0/authoriz
    '''
    def __init__(self, client_id=None, client_secret=None, redirect_uri=None, state=None):
        self.client_id = client_id or settings.QQ_CLIENT_ID
        self.client_secret = client_secret or settings.QQ_CLIENT_SECRET
        self.redirect_uri = redirect_uri or settings.QQ_REDIRECT_URI
        self.state = state or settings.QQ_STATE

    def get_qq_login_url(self):
        '''或取qq登录的网址'''
        params = {
            'response_type': 'code',
            'client_id': self.client_id,
            'redirect_uri': self.redirect_uri,
            'state': self.state,
            'scope': 'get_user_info'
        }
        url = 'https://graph.qq.com/oauth2.0/authorize?' + urlencode(params)
        return url
    def get_qq_access_token(self, code):

        params = {
            'grant_type': 'authorization_code',
            'client_id': self.client_id,
            'client_secret': self.client_secret,
            'code': code,
            'redirect_uri': self.redirect_uri,
        }
        url = 'https://graph.qq.com/oauth2.0/token?' + urlencode(params)

        #向qq服务器发送信息
        response = urlopen(url)
        msg_info = response.read().decode()
        msg_dict = parse_qs(msg_info)
        access_token = msg_dict.get('access_token', None)
        if not access_token:
            logger.error('code=%s msg=%s' % (msg_dict.get('code'), msg_dict.get('msg')))
            raise QQAPIError
        return access_token[0]


    def get_qq_openid(self, access_token):
        url = 'https://graph.qq.com/oauth2.0/me?access_token=' + access_token

        response = urlopen(url)
        msg_info = response.read().decode()
        try:
            msg_dict = json.loads(msg_info[10:-4])
        except Exception:
            msg_dict = parse_qs(msg_info)
            logger.error('code=%s msg=%s' % (msg_dict.get('code'), msg_dict.get('msg')))
            raise QQAPIError
        openid = msg_dict.get('openid', None)
        return openid

    @staticmethod
    def generate_save_user_token(openid):
        serializer = Serializer(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
        data = {'openid': openid}
        token = serializer.dumps(data)
        return token.decode()
    @staticmethod
    def check_save_user_token(token):
        serializer = Serializer(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
        try:
            data = serializer.loads(token)
        except BadData:
            return None
        else:
            return data.get('openid')
